//
//  KKNetwork.m
//  Questionnaire
//
//  Created by leo on 16/1/24.
//  Copyright © 2016年 leo. All rights reserved.
//

#import "KKNetworkManager.h"



@implementation KKNetworkManager


#pragma mark - Post methods

+ (void)sendPostRequest:(KKNetworkRequest *)request success:(KKNetworkSuccessHandle)successful faile:(KKNetworkFaileHandle)faile {
    
    NSMutableURLRequest *URLRequest = [self private_sessionTaskWithRequest: request];
    [URLRequest setHTTPBody: request.postData];
    
    NSURLSession *session = [NSURLSession sharedSession];
    //  子线程运行
    
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible: true];
    __weak typeof(self) weakSelf = self;
    NSURLSessionDataTask *task = [session dataTaskWithRequest: URLRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        [weakSelf private_processingNetworkRequest: request responseData: data error: error success: successful faile: faile];
    }];
    
    [task resume];
}

+ (void)sendGetRequest:(KKNetworkRequest *)request success:(KKNetworkSuccessHandle)successful faile:(KKNetworkFaileHandle)faile {
    
    NSMutableURLRequest *URLRequest = [self private_sessionTaskWithRequest: request];
    [URLRequest setHTTPMethod:@"GET"];
    
    NSURLSession *session = [NSURLSession sharedSession];
    //  子线程运行
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible: true];
    
    __weak typeof(self) weakSelf = self;
    NSURLSessionDataTask *task = [session dataTaskWithRequest: URLRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        [weakSelf private_processingNetworkRequest: request responseData: data error: error success: successful faile: faile];
    }];
    
    [task resume];
}

+ (void)sendUploadImageRequest:(KKNetworkRequest*)request image:(UIImage*)image success:(KKNetworkSuccessHandle)successful faile:(KKNetworkFaileHandle)faile {
    
    NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
    NSString *fileName = request.requestParmeters[@"file_name"];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //接收类型不一致请替换一致text/html或别的
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                         @"text/html",
                                                         @"image/jpeg",
                                                         @"image/png",
                                                         @"application/octet-stream",
                                                         @"text/json",
                                                         nil];
    NSURLSessionDataTask *task = [manager POST:request.requestURL parameters: request.requestParmeters constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
        //上传的参数(上传图片，以文件流的格式)
        [formData appendPartWithFileData:imageData
                                    name:@"file"
                                fileName:fileName
                                mimeType:@"image/jpg"];
        
    } progress:^(NSProgress *_Nonnull uploadProgress) {
        //打印下上传进度
    } success:^(NSURLSessionDataTask *_Nonnull task, id _Nullable responseObject) {
        NSLog(@"responseObject = %@", responseObject);
        //上传成功
    } failure:^(NSURLSessionDataTask *_Nullable task, NSError * _Nonnull error) {
        //上传失败
        NSLog(@"error = %@", error);
    }];
}


#pragma mark - Private methods

+ (NSMutableURLRequest*)private_sessionTaskWithRequest:(KKNetworkRequest*)networkRequest {
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: networkRequest.requestURL]];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setTimeoutInterval: 15.0f];
    [request setHTTPMethod: @"GET"];
    return request;
}

+ (void)private_processingNetworkRequest:(KKNetworkRequest*)request responseData:(NSData*)responseData error:(NSError*)error success:(KKNetworkSuccessHandle)successful faile:(KKNetworkFaileHandle)faile{
    
    __weak typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        //  回到主线程
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible: false];
        if (error) {
            
            NSDictionary *userInfo = error.userInfo;
            NSString *errorString = userInfo[NSLocalizedDescriptionKey];
            [weakSelf showResponseErrorWithRequest: request error: errorString];
            if (faile) {
                faile(error.description);
            }
            return;
        }
        
        NSString *parserError = nil;
        KKNetworkResponse *responseObject = [KKNetworkResponse responseWithData: responseData request:request error: &parserError];
        if (responseObject == nil && parserError != nil) {
            [weakSelf showResponseErrorWithRequest: request error: parserError];
            if (faile) {
                faile(parserError);
            }
        }
        else {
            if (successful) {
                successful(responseObject);
            }
        }
    });
}

+ (void)showResponseErrorWithRequest:(KKNetworkRequest *)request error:(NSString *)errorString {
    
    if (!request.showAlert) {
        return;
    }
    
    NSLog(@"errorString = %@", errorString);
}

@end
